package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.api.content.model.dto.CourseBaseDTO;
import com.xuecheng.api.content.model.dto.CourseTeacherDTO;
import com.xuecheng.api.content.model.dto.TeachplanDTO;
import com.xuecheng.api.content.model.qo.QueryCourseModel;
import com.xuecheng.api.system.model.dto.CourseCategoryDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.domain.response.RestResponse;
import com.xuecheng.common.enums.common.CommonEnum;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.common.enums.content.CourseChargeEnum;
import com.xuecheng.common.enums.content.CourseModeEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.JsonUtil;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.content.agent.SystemApiAgent;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.convert.CourseBaseConvert;
import com.xuecheng.content.convert.CoursePubConver;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.CourseMarket;
import com.xuecheng.content.entity.CoursePub;
import com.xuecheng.content.entity.Teachplan;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
@SuppressWarnings("All") //扫黄
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {


    @Autowired
    private CourseMarketService courseMarketService;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private SystemApiAgent systemAgent;

    @Autowired
    private CoursePubService coursePubService;

    @Autowired
    private CourseTeacherService courseTeacherService;

    /**
     * 分页条件查询课程基本信息
     *
     * @param params
     * @param model
     * @return
     */
    @Override
    public PageVO QueryCourseList(PageRequestParams params, QueryCourseModel model, Long compantId) {

        //判断分页数据是否合法
        if (params.getPageNo() < 1) {

            //默认值
            params.setPageNo(PageRequestParams.DEFAULT_PAGE_NUM);
        }

        if (params.getPageSize() < 1) {

            //默认值
            params.setPageSize(PageRequestParams.DEFAULT_PAGE_SIZE);
        }

        //查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();

        //课程审核状态
        queryWrapper.eq(StringUtil.isNotBlank(model.getAudiStatus()), CourseBase::getAuditStatus, model.getAudiStatus());

        //课程名称
        queryWrapper.like(StringUtil.isNotBlank(model.getCourseName()), CourseBase::getName, model.getCourseName());

        //公司id  (当公司id不为空时，就是机构查询，id为空时，就是运营平台后台查询)
        queryWrapper.eq(!ObjectUtils.isEmpty(compantId), CourseBase::getCompanyId, compantId);

        //分页条件,当前页码数和每页条数
        Page<CourseBase> page = new Page<>(params.getPageNo(), params.getPageSize());

        //调用MP分页查询方法
        Page<CourseBase> pageResult = this.page(page, queryWrapper);

        //获取数据的总条数
        long total = pageResult.getTotal();

        //获取数据结果集
        List<CourseBase> records = pageResult.getRecords();

        //创建一个空集合
        List<CourseBaseDTO> dtoList = Collections.emptyList();

        //将po对象转为dto对象
        if (!CollectionUtils.isEmpty(records)) {
            dtoList = CourseBaseConvert.INSTANCE.entitys2dtos(records);
        }

        //封装到PageVo对象
        PageVO pageVO = new PageVO(dtoList, total, params.getPageNo(), params.getPageSize());

        //返回
        return pageVO;
    }


    /**
     * 保存课程信息内容
     *
     * @param courseBaseDTO
     * @return
     */
    @Transactional // 插入需要开启事务
    public com.xuecheng.api.content.model.dto.CourseBaseDTO creatCourseBase(CourseBaseDTO courseBaseDTO) {

        //判断必须项是否为空
        verifyCourseMsg(courseBaseDTO);

        //将courseBaseDTO转为Po（CourseBase）
        CourseBase courseBase = CourseBaseConvert.INSTANCE.dto2po(courseBaseDTO);

        //给添加的课程审核状态赋值，新添加的属于未提交
        courseBase.setAuditStatus(CourseAuditEnum.AUDIT_UNPAST_STATUS.getCode());

        //调用添加的方法
        boolean save = this.save(courseBase);

        //判断是否添加成功
        if (!save) {
            //throw new RuntimeException("课程信息添加失败");
            ExceptionCast.cast(ContentErrorCode.E_120001);
        }

        //添加课程营销信息
        CourseMarket courseMarket = new CourseMarket();

        //判断该课程是否收费，如果收费需要给价格赋值
        if (CourseChargeEnum.CHARGE_YES.getCode().equals(courseBaseDTO.getCharge())) {
            //是否收费，是
            courseMarket.setCharge(courseBaseDTO.getCharge());
            //价格
            float price = courseBaseDTO.getPrice().floatValue();
            courseMarket.setPrice(price);
        } else {
            //免费
            courseMarket.setCharge(CourseChargeEnum.CHARGE_NO.getCode());
        }

        //课程id标识，mp保存数据后，会将数据赋值给实体类
        courseMarket.setCourseId(courseBase.getId());

        //调用添加方法
        boolean save2 = courseMarketService.save(courseMarket);

        //判断是否添加成功
        if (!save2) {
            //throw new RuntimeException("课程营销内容添加失败");
            ExceptionCast.cast(ContentErrorCode.E_120107);
        }

        //将po对象转转为DTO
        CourseBaseDTO ResultCourseBaseDTO1 = CourseBaseConvert.INSTANCE.entity2dto(courseBase);

        //判断是否收费
        if (CourseChargeEnum.CHARGE_YES.getCode().equals(courseMarket.getCharge())) {

            //收费
            ResultCourseBaseDTO1.setCharge(courseMarket.getCharge());

            //价格
            BigDecimal bigDecimal = new BigDecimal(courseMarket.getPrice());
            ResultCourseBaseDTO1.setPrice(bigDecimal);
        }

        //返回数据
        return ResultCourseBaseDTO1;
    }


    //判断是否为空
    private void verifyCourseMsg(CourseBaseDTO courseBaseDTO) {

        if (StringUtil.isBlank(courseBaseDTO.getName())) {
            //throw  new RuntimeException("课程名称不能为空");
            ExceptionCast.cast(ContentErrorCode.E_120004);
        }
        if (StringUtil.isBlank(courseBaseDTO.getMt())) {
            //throw new RuntimeException("课程大分类不能为空");
            ExceptionCast.cast(ContentErrorCode.E_120018);
        }
        if (StringUtil.isBlank(courseBaseDTO.getSt())) {
            //throw new RuntimeException("课程小分类不能为空");
            ExceptionCast.cast(ContentErrorCode.E_120019);
        }
        if (ObjectUtils.isEmpty(courseBaseDTO.getCompanyId())) {
            //throw new RuntimeException("公司id不能为空");
            ExceptionCast.cast(ContentErrorCode.E_120020);
        }
        if (StringUtil.isBlank(courseBaseDTO.getGrade())) {
            //throw new RuntimeException("课程等级不能为空");
            ExceptionCast.cast(ContentErrorCode.E_120007);
        }
        if (StringUtil.isBlank(courseBaseDTO.getTeachmode())) {
            //throw new RuntimeException("课程授课模式不能为空");
            ExceptionCast.cast(ContentErrorCode.E_120006);
        }
    }


    /*
     * 业务分析：
     *   1.是否开启事务（不需要）
     *   2.判断关键数据
     *       courseBaseId，companyId
     *   3.根据id查询课程基本信息（优化：将companyId作为查询条件）
     *   4.判断课程是否存在，如果存在判断是否删除（1：使用，0：删除）
     *   5.查询课程营销数据，并判断是否存在
     *   6.将当前数据转为dto数据并返回
     * */

    /**
     * 根据id查询课程基本信息
     *
     * @param courseBaseId
     * @param companyId
     * @return
     */
    public CourseBaseDTO queryById(Long courseBaseId, Long companyId) {

        //判断关键数据是否为空
        if (ObjectUtils.isEmpty(courseBaseId) || ObjectUtils.isEmpty(companyId)) {
            //throw new RuntimeException("关键数据不匹配");
            ExceptionCast.cast(ContentErrorCode.E_120009);
        }

        //构造查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();

        //添加查询条件
        queryWrapper.eq(CourseBase::getCompanyId, companyId);

        queryWrapper.eq(CourseBase::getId, courseBaseId);

        CourseBase courseBase = this.getOne(queryWrapper);

        //判断课程是否存在
        if (ObjectUtils.isEmpty(courseBase)) {
            //throw new RuntimeException("课程信息不存在");
            ExceptionCast.cast(ContentErrorCode.E_120013);
        }

        if (courseBase.getStatus().equals(CommonEnum.DELETE_FLAG.getCodeInt())) {
            //throw new RuntimeException("课程已删除");
            ExceptionCast.cast(ContentErrorCode.E_120021);
        }

        //查询课程营销信息
        LambdaQueryWrapper<CourseMarket> queryWrapper1 = new LambdaQueryWrapper<>();

        //根据课程id查询
        queryWrapper1.eq(CourseMarket::getCourseId, courseBaseId);

        CourseMarket courseMarket = this.courseMarketService.getOne(queryWrapper1);

        //判断课程营销信息是否存在
        if (ObjectUtils.isEmpty(courseMarket)) {
            //throw new RuntimeException("课程营销信息不存在");
            ExceptionCast.cast(ContentErrorCode.E_120101);
        }

        //将当前数据转为Dto返回
        CourseBaseDTO courseBaseDTO = CourseBaseConvert.INSTANCE.entity2dto(courseBase);

        //当前课程是否收费
        if (CourseChargeEnum.CHARGE_YES.getCode().equals(courseMarket.getCharge())) {
            //将价格赋值给给CourserBaeDTO返回
            courseBaseDTO.setCharge(courseMarket.getCharge());
            courseBaseDTO.setPrice(new BigDecimal(courseMarket.getPrice()));
        }

        return courseBaseDTO;
    }


    /*
     * 业务分析：
     *   1.判断关键数据
     *   2.判断修改课程基本信息数据的id是否存在对应的课程数据
     *      修改的数据，必须要有id值
     *   3.判断课程是否已删除
     *   4.判断课程的审核状态
     *   5.判断课程是否是同一家教学机构
     *   6.修改课程数据
     *       1.课程基本信息
     *       2.课程营销数据
     *   7.将修改后的数据转为dto返回
     *
     * */
    @Transactional //开启事务
    public CourseBaseDTO modifyCourse(CourseBaseDTO courseBaseDTO) {

        //判断关键数据是否为空
        verifyCourseMsg(courseBaseDTO);

        //判断要修改的课程id是否在数据库存在
        CourseBase courseBase = this.getById(courseBaseDTO.getCourseBaseId());

        if (ObjectUtils.isEmpty(courseBase)) {
            //throw new RuntimeException("该课程不存在");
            ExceptionCast.cast(ContentErrorCode.E_120013);

        }

        //判断该课程是否已删除
        if (CommonEnum.DELETE_FLAG.getCode().equals(courseBase.getStatus())) {
            //throw new RuntimeException("该课程已删除");
            ExceptionCast.cast(ContentErrorCode.E_120021);

        }

        //判断课程的审核状态
        if (CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(courseBase.getAuditStatus()) ||
                CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(courseBase.getAuditStatus()) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(courseBase.getAuditStatus())) {
            //throw new RuntimeException("课程已提交或审核已通过");
            ExceptionCast.cast(ContentErrorCode.E_120011);

        }

        //判断该课程是否属于这家教育机构
        if (!ObjectUtils.nullSafeEquals(courseBaseDTO.getCompanyId(), courseBase.getCompanyId())) {
            //throw new RuntimeException("无权访问");
            ExceptionCast.cast(CommonErrorCode.E_403000);
        }

        //将dto转为po
        CourseBase dto2po = CourseBaseConvert.INSTANCE.dto2po(courseBaseDTO);

        //更新数据
        boolean update = this.updateById(dto2po);

        //判断是否更新成功
        if (!update) {
            //throw new RuntimeException("更新课程信息失败");
            ExceptionCast.cast(ContentErrorCode.E_120017);

        }

        //更新课程营销信息
        LambdaUpdateWrapper<CourseMarket> updateWrapper = new LambdaUpdateWrapper<>();

        //课程id
        updateWrapper.eq(CourseMarket::getCourseId, courseBaseDTO.getCourseBaseId());

        //课程是否收费
        updateWrapper.eq(CourseMarket::getCharge, courseBaseDTO.getCharge());

        //课程价格
        updateWrapper.set(CourseMarket::getPrice, courseBaseDTO.getPrice());

        boolean update1 = this.courseMarketService.update(updateWrapper);

        if (!update) {
            //throw new RuntimeException("课程营销信息更新失败");
            ExceptionCast.cast(ContentErrorCode.E_120107);

        }

        //将修改后的数据转为dto返回
        CourseBaseDTO baseDTO = CourseBaseConvert.INSTANCE.entity2dto(courseBase);


        baseDTO.setPrice(courseBaseDTO.getPrice());

        baseDTO.setCharge(courseBaseDTO.getCharge());
/*
        //查询课程营销信息
        LambdaQueryWrapper<CourseMarket> queryWrapper1 = new LambdaQueryWrapper<>();

        //根据课程id查询
        queryWrapper1.eq(CourseMarket::getCourseId,courseBase.getId());

        CourseMarket courseMarket = this.courseMarketService.getOne(queryWrapper1);

        //将修改后的课程信息转为dto
        baseDTO = CourseBaseConvert.INSTANCE.marker2dto(courseMarket);*/

        return baseDTO;
    }


    /**
     * 根据课程id删除课程
     *
     * @param courseBaseId 课程id
     */
    @Override
    public void deleteCourseBase(Long courseBaseId, Long companyId) {

        //判断数据的合法性
        if (ObjectUtils.isEmpty(courseBaseId) || ObjectUtils.isEmpty(companyId)) {
            //throw new RuntimeException("传入数据不合法");
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        //根据id查询课程信息
        CourseBase courseBase = this.getById(courseBaseId);

        //判断该课程是否存在
        if (ObjectUtils.isEmpty(courseBase)) {
            //throw  new RuntimeException("该课程不存在");
            ExceptionCast.cast(ContentErrorCode.E_120013);
        }

        //判断该课程是否属于这家公司
        if (!companyId.equals(courseBase.getCompanyId())) {
            //throw new RuntimeException("无权访问");
            ExceptionCast.cast(CommonErrorCode.E_403000);
        }

        //判断课程的审核状态
        if (CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(courseBase.getAuditStatus()) ||
                CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(courseBase.getAuditStatus()) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(courseBase.getAuditStatus())) {
            //throw new RuntimeException("课程已提交或审核已通过");
            ExceptionCast.cast(ContentErrorCode.E_120011);
        }

        //删除课程信息，修改课程状态为删除态
        LambdaUpdateWrapper<CourseBase> updateWrapper = new LambdaUpdateWrapper<>();

        //跟改为删除状态
        updateWrapper.set(CourseBase::getStatus, CommonEnum.DELETE_FLAG.getCode());

        //通过id更改
        updateWrapper.eq(CourseBase::getId, courseBaseId);

        //更该时间
        updateWrapper.set(CourseBase::getChangeDate, LocalDateTime.now());

        boolean update = this.update(updateWrapper);

        if (!update) {
            //throw new RuntimeException("删除课程信息失败");
            ExceptionCast.cast(ContentErrorCode.E_120017);
        }
    }


    //机构提交课程信息
    @Override
    @Transactional
    public void submitCourseBase(Long courseBaseId, Long companyId) {

        //判断关键数据
        if (ObjectUtils.isEmpty(companyId) || ObjectUtils.isEmpty(courseBaseId)) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        //判断此课程信息是否存在
        CourseBase courseBase = this.getById(courseBaseId);

        if (ObjectUtils.isEmpty(courseBase)) {
            ExceptionCast.cast(ContentErrorCode.E_120013);
        }

        //判断课程信息是否被删除
        if (CommonEnum.DELETE_FLAG.getCodeInt().equals(courseBase.getStatus())) {
            ExceptionCast.cast(ContentErrorCode.E_120021);
        }

        //判断此课程是否是同一家机构
        if (!ObjectUtils.nullSafeEquals(companyId, courseBase.getCompanyId())) {
            ExceptionCast.cast(CommonErrorCode.E_403000);
        }

        //判断此课程的审核状态（未提交、审核未通过的才能提交）
        if (CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(courseBase.getAuditStatus()) ||
                CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(courseBase.getAuditStatus()) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(courseBase.getAuditStatus())) {
            ExceptionCast.cast(ContentErrorCode.E_120014);
        }

        //将课程状态改为已提交
        LambdaUpdateWrapper<CourseBase> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.eq(CourseBase::getId, courseBaseId);

        updateWrapper.set(CourseBase::getAuditStatus, CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode());

        //修改数据库
        boolean update = this.update(updateWrapper);

        //判断修改是否成功
        if (!update) {
            ExceptionCast.cast(ContentErrorCode.E_120017);
        }
    }


    //运营平台审核教育机构课程
    @Override
    public void modifyCourseAudit(CourseBaseDTO courseBaseDTO) {

        //课程id
        Long courseBaseId = courseBaseDTO.getCourseBaseId();

        //审核状态
        String auditStatus = courseBaseDTO.getAuditStatus();

        //判断关键数据是否存在
        if (StringUtil.isBlank(auditStatus) || ObjectUtils.isEmpty(courseBaseId)) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        //判断此课程信息是否存在
        CourseBase courseBase = this.getById(courseBaseId);

        if (ObjectUtils.isEmpty(courseBase)) {
            ExceptionCast.cast(ContentErrorCode.E_120013);
        }

        //判断此课程信息是否是删除态
        if (CommonEnum.DELETE_FLAG.getCodeInt().equals(courseBase.getStatus())) {
            ExceptionCast.cast(ContentErrorCode.E_120021);
        }

        //判断此课程是否被教育机构提交（只有提交的课程才能被审核）
        if (!CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(courseBase.getAuditStatus())) {
            ExceptionCast.cast(ContentErrorCode.E_120017);
        }

        //运营平台只能修改为两个状态（审核通过和审核未通过两个状态）
        if (!CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(auditStatus) &&
                !CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus)) {
            ExceptionCast.cast(ContentErrorCode.E_120014);
        }

        //修改审核状态、审核次数、审核意见
        LambdaUpdateWrapper<CourseBase> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.eq(CourseBase::getId, courseBaseId);

        //审核状态
        updateWrapper.set(CourseBase::getAuditStatus, auditStatus);

        //审核次数(修改时审核次数要+1)
        Integer auditNums = courseBase.getAuditNums() + 1;

        updateWrapper.set(CourseBase::getAuditNums, auditNums);

        //审核意见
        updateWrapper.set(CourseBase::getAuditMind, courseBaseDTO.getAuditMind());

        boolean update = this.update(updateWrapper);

        //判断是否审核成功
        if (!update) {
            ExceptionCast.cast(ContentErrorCode.E_120017);
        }
    }

    //课程预览
    public Map<String, Object> CoursePreview(Long courseBaseId, Long companyId) {

        //创建pub信息并保存
        CoursePub coursePub = generateCoursePub(courseBaseId, companyId);

        //获取pub中的信息，封装成map
        HashMap<String, Object> dataMap = seleteCoursePub(coursePub);

        return dataMap;
    }

    //创建并保存pub
    private CoursePub generateCoursePub(Long courseBaseId, Long companyId) {
        //1.判断关键数据
        if (ObjectUtils.isEmpty(courseBaseId) || ObjectUtils.isEmpty(companyId)) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        //2.获得课程基础信息数据
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseBase::getId, courseBaseId);
        CourseBase courseBase = this.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(courseBase)) {
            ExceptionCast.cast(ContentErrorCode.E_120013);
        }
        if (CommonEnum.DELETE_FLAG.getCodeInt().equals(courseBase.getStatus())) {
            ExceptionCast.cast(ContentErrorCode.E_120021);
        }
        if (CourseAuditEnum.AUDIT_COMMIT_STATUS.equals(courseBase.getAuditStatus()) ||
                CourseAuditEnum.AUDIT_PASTED_STATUS.equals(courseBase.getAuditStatus()) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.equals(courseBase.getAuditStatus())) {
            ExceptionCast.cast(ContentErrorCode.E_120015);
        }

        if (!ObjectUtils.nullSafeEquals(companyId, courseBase.getCompanyId())) {
            ExceptionCast.cast(CommonErrorCode.E_100108);
        }
        CoursePub coursePub = CoursePubConver.INSTANCE.courseBase2coursePub(courseBase);
        coursePub.setCourseId(courseBaseId);


        //3.获取课程营销数据
        LambdaQueryWrapper<CourseMarket> marketQueryWrapper = new LambdaQueryWrapper<>();
        marketQueryWrapper.eq(CourseMarket::getCourseId, courseBaseId);
        CourseMarket courseMarket = courseMarketService.getOne(marketQueryWrapper);
        if (ObjectUtils.isEmpty(courseMarket)) {
            ExceptionCast.cast(ContentErrorCode.E_120101);
        }
        coursePub.setCharge(courseMarket.getCharge());
        coursePub.setPrice(courseMarket.getPrice());
        String marketJson = JsonUtil.objectTojson(courseMarket);
        coursePub.setMarket(marketJson);

        //4.获取课程计划数据
        TeachplanDTO teachplanDTO = teachplanService.queryTeachplan(courseBaseId, companyId);
        if (ObjectUtils.isEmpty(teachplanDTO)) {
            ExceptionCast.cast(ContentErrorCode.E_120402);
        }
        String teachplanJson = JsonUtil.objectTojson(teachplanDTO);
        coursePub.setTeachplan(teachplanJson);
        //5.获取教师数据
        List<CourseTeacherDTO> teacherDTOs = this.courseTeacherService.queryCourseTeacher(courseBaseId, companyId);
        String teachersJson = JsonUtil.objectTojson(teacherDTOs);
        coursePub.setTeachers(teachersJson);


        //6.查询课程分类
        RestResponse<CourseCategoryDTO> stResponse = systemAgent.queryCourseCategoryById(courseBase.getSt());
        if (!stResponse.isSuccessful()) {
            ExceptionCast.cast(ContentErrorCode.E_120019);
        }
        RestResponse<CourseCategoryDTO> mtResponse = systemAgent.queryCourseCategoryById(courseBase.getMt());
        if (!mtResponse.isSuccessful()) {
            ExceptionCast.cast(ContentErrorCode.E_120018);
        }
        coursePub.setMt(mtResponse.getResult().getName());
        coursePub.setSt(stResponse.getResult().getName());

        //7.保存或修改课程发布数据
        LambdaQueryWrapper<CoursePub> coursePubQueryWrapper = new LambdaQueryWrapper<>();
        coursePubQueryWrapper.eq(CoursePub::getCourseId, courseBaseId);
        //一个课程只能有一个课程发布信息
        CoursePub coursePubPo = coursePubService.getOne(coursePubQueryWrapper);
        if (ObjectUtils.isEmpty(coursePubPo)) {
            //为空保存发布信息
            boolean result = coursePubService.save(coursePub);
            if (!result) {
                ExceptionCast.cast(ContentErrorCode.E_120205);
            }
        }

        //修改只需要把旧数据(coursePub)的id给新数据(pubPo)即可
        coursePub.setId(coursePubPo.getId());
        boolean result = coursePubService.updateById(coursePub);
        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_120206);
        }

        return coursePub;
    }

    //封装数据模型
    private HashMap<String, Object> seleteCoursePub(CoursePub coursePub) {

        HashMap<String, Object> dataMap = new HashMap<>();

        // 2.1 课程发布数据封装
        dataMap.put("coursePub", coursePub);

        // 2.2 课程营销数据封装 - JSON格式

        String market = coursePub.getMarket();
        CourseMarket courseMarket = JsonUtil.jsonToObject(market, CourseMarket.class);
        dataMap.put("courseMarket", courseMarket);

        // 2.3 课程计划数据封装
        TeachplanDTO teachplanDTO = JsonUtil.jsonToObject(coursePub.getTeachplan(), TeachplanDTO.class);
        dataMap.put("teachplanNode", teachplanDTO);

        // 2.4 获得教育模式信息
        CourseModeEnum[] values = CourseModeEnum.values();
        dataMap.put("courseTeachModeEnums", values);

        return dataMap;


    }


}
